/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

package com.bullionxpress.server.impl;

import java.rmi.RemoteException;
import com.bullionxpress.shared.service.DuplicateInstrumentIDException;
import com.bullionxpress.shared.service.InstrumentNotFoundException;
import com.bullionxpress.shared.service.InvalidInstrumentIDFormatException;
import com.bullionxpress.shared.service.InstrumentDatabase;
import com.bullionxpress.shared.model.Instrument;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import com.bullionxpress.shared.util.Log;

public class InstrumentManager extends java.rmi.server.UnicastRemoteObject implements InstrumentDatabase {

    public InstrumentManager() throws RemoteException {
        //What should go in the constructor?
        connect();
    }
    Connection conn = null;
    Statement statement = null;

    public void connect() {

        try {
            conn = DatabaseManager.getConnection();

            try {
                statement = conn.createStatement();
                statement.executeUpdate("CREATE TABLE IF NOT EXISTS instruments (symbol varchar(32), name varchar(256), description varchar(1024))");
                    
                // debug ? 
                statement.executeUpdate("INSERT INTO instruments VALUES ('GOLD', 'Gold', 'This is a Gold Instrument')");
                statement.executeUpdate("INSERT INTO instruments VALUES ('SILVER', 'Silver', 'This is a Silver Instrument')");
                statement.executeUpdate("INSERT INTO instruments VALUES ('BTC', 'Bitcoin', 'This is a Bitcoin Instrument')");

            } catch (Exception ex) {
                //Log.info(ex);
                //ex.printStackTrace();
            }

        } catch (Exception ex) {
            Log.info(ex);
            ex.printStackTrace();
        }
    }

    public Instrument[] getAll() {

        try {

            String query = "SELECT * FROM instruments";
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            ResultSet result = statement.executeQuery(query);
            Vector v = new Vector();
            while (result.next()) {
                Instrument Instrument = get(result.getString("symbol"));
                v.addElement(Instrument);
            }
            Instrument[] instrumentList = new Instrument[v.size()];
            for (int i = 0; i < v.size(); i++) {
                instrumentList[i] = (Instrument) v.get(i);
            }
            return instrumentList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public Instrument get(String symbol) throws InstrumentNotFoundException {
        if (symbol == null) {
            throw new IllegalArgumentException();
        }
        System.out.println("instrument:" + symbol);
        String query = "SELECT * FROM instruments WHERE symbol = '" + symbol + "'";
        ResultSet result = null;
        //System.out.println(query);
        boolean r = false;
        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            result = statement.executeQuery(query);
            r = result.next();
        } catch (Exception ex) {
        }

        if (r) {
            Instrument Instrument = new Instrument(symbol);
            try {
                Instrument.setDescription(result.getString("description"));
                //Instrument.setSymbol(symbol);
                //Instrument.setName(result.getString("name"));
            } catch(Exception ex){
                ex.printStackTrace();
                throw new InstrumentNotFoundException();
            }
            return Instrument;
        } else {
            throw new InstrumentNotFoundException();
        }
    }

    public void add(Instrument b) throws DuplicateInstrumentIDException, InvalidInstrumentIDFormatException {

        if (b == null) {
            throw new IllegalArgumentException();
        } else if (b.getSymbol() == null) {
            throw new InvalidInstrumentIDFormatException();
        }

        try {
            Instrument a = get(b.getSymbol());
            throw new DuplicateInstrumentIDException();
        } catch(InstrumentNotFoundException ex){
            
        }

        String query = "INSERT INTO instruments (symbol, name, description)  VALUES ( '" + b.getSymbol() + "', '" + b.getSymbol() + "', '" + b.getDescription() + "')";
        int n = 0;
        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            n = statement.executeUpdate(query);
        } catch (SQLException ex) {
            ex.printStackTrace();
            Log.info(ex);
        }
        Log.info("INSERT " + n);
        if (n != 1) {
            throw new DuplicateInstrumentIDException();
        }
    }

    public void delete(String symbol) throws InstrumentNotFoundException, InvalidInstrumentIDFormatException {

        if (symbol == null) {
            throw new IllegalArgumentException();
        } 

        String sql = "DELETE FROM instruments WHERE symbol = '" + symbol + "'";

        int n = 0;
        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            n = statement.executeUpdate(sql);
            Log.info("DELETE:" + n);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        if (n < 1) {
            throw new InstrumentNotFoundException();
        }

    }

    public void close() {
    }

    public int count() {
        int r = 0;
        Instrument[] b = getAll();
        return b.length;
    }



}
